// 重命名
import React from 'react';
import { Form, Input, message, Modal } from 'antd';
import { saveChartComponent } from 'src/services/AnalyseManage';

interface Iprops {
	modalVisible: boolean;
	updateData?: any;
	handleCancel: Function;
	onSuccess: () => void;
}

// eslint-disable-next-line react/display-name
const RenameItem = React.forwardRef( ( props: Iprops, formRef: any ) => {
	const [ form ] = Form.useForm();

	const handleCancel = () => {
		form.resetFields();
		props.handleCancel();
	};

	const handleOk = () => {
		form.validateFields()
			.then( ( value ) => {
				handleSave( value );
			} )
			.catch( ( info ) => {
				message.warning( '请完善信息' );
			} );
	};

	// 重名名
	const handleSave = async ( values: any ) => {
		const data = {
			componentId: props.updateData.componentId,
			describe: values.des,
			name: values.name,
			content: JSON.stringify( props.updateData.content ),
			parentId: props.updateData.parentId,
		};

		const res = await saveChartComponent( data );

		if ( res.data && res.data.success ) {
			message.success( '保存成功' );
			handleCancel();
			props.onSuccess();
		}

	};

	return (
		<Modal okText={'确定'} visible={props.modalVisible} cancelText={'取消'} onCancel={handleCancel} onOk={handleOk} title="图表重命名">
			<Form form={form} ref={formRef} labelCol={{ span: 4 }} initialValues={props.updateData}>
				<Form.Item label={'图表名称'} rules={[ { required: true, message: '名称不能为空' } ]} name="name">
					<Input autoComplete="off" />
				</Form.Item>
				<Form.Item label={'图表描述'} name="describe">
					<Input />
				</Form.Item>
			</Form>
		</Modal>
	);
} );

export default RenameItem;
